package com.bill99.golden.inf.sso.util;

import javax.servlet.ServletContext;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import com.bill99.golden.inf.sso.client.IssoClient;
import com.bill99.golden.inf.sso.client.SSOInfo;
import com.bill99.golden.inf.sso.client.SsoClientHttp;
import com.bill99.golden.inf.sso.session.LocalSession;
import com.bill99.golden.inf.sso.session.SessionService;

public class SSOUtil {
	private static Log log = LogFactory.getLog(SSOUtil.class);
	private static final String defaultDomain = ".51799517.com";
	private static final String tokenCookieName = "T51799517";
	private static final String tokenCookieNameSecure = "T51799517SECURE";
	private static final int maxAge = 3600 * 24;

	public static String getDomain(final HttpServletRequest req) {
		String url = req.getRequestURL().toString();
		String uri = req.getRequestURI();
		int end = url.indexOf(uri);
		int st = url.indexOf("://");
		if (st > 0) {
			st += "://".length();
		} else {
			st = 0;
		}
		String domain = url.substring(st, end);
		return domain;
	}

	public static LocalSession getLocalSession(final HttpServletRequest request) {
		String token = SSOUtil.getToken(request);
		return SessionService.getLocalSession(token);
	}

	public static boolean isValidateToken(String token) {
		if (token != null && token.trim().length() > 4
				&& token.toUpperCase().equals(token)) {
			return true;
		} else {
			return false;
		}
	}

	public static SSOInfo getSSOInfo(final HttpSession session) {
		return (SSOInfo) session.getAttribute(IssoClient.SSO_INFO_NAME);
	}

	public static SSOInfo getSSOInfo(final HttpServletRequest request) {
		return (SSOInfo) request.getSession().getAttribute(IssoClient.SSO_INFO_NAME);
	}

	private static void setCookie(HttpServletResponse response, String name, String value, String domain, boolean isSecure) {
		Cookie cookie = new Cookie(name, value);
		cookie.setPath("/");
		if (null==domain){
			cookie.setDomain(SSOUtil.defaultDomain);
		}else{
			cookie.setDomain(domain);
		}
		cookie.setMaxAge(SSOUtil.maxAge);
		cookie.setSecure(isSecure);
		response.addCookie(cookie);
	}

	public static void setCookie(HttpServletResponse response, String name, String value, String domain) {
		setCookie(response, name, value, domain, false);
		setCookie(response, name + "Secure", value, domain, true);
	}

	public static void setTokenCookie(HttpServletResponse response, String token, String domain) {
		setCookie(response, SSOUtil.tokenCookieName, token, domain, false);
		setCookie(response, SSOUtil.tokenCookieNameSecure, token, domain, true);
	}

	private static String getCookieValue(HttpServletRequest request, String name) {
		Cookie[] cks = request.getCookies();
		if (cks != null) {
			for (int i = 0; i < cks.length; i++) {
				if (cks[i].getName().equals(name))
					return cks[i].getValue();
			}
		}
		return null;
	}

	public static String getCookie(HttpServletRequest request, String cookieName) {
		String val = getCookieValue(request, cookieName);
		if (val != null && val.trim().length() > 0) {
			return val;
		}
		val = getCookieValue(request, cookieName + "Secure");
		if (val != null && val.trim().length() > 0) {
			return val;
		}
		return null;
	}

	public static String getToken(HttpServletRequest request) {
		String token = getCookieValue(request, SSOUtil.tokenCookieName);
		if (token != null && token.trim().length() > 0) {
			return token;
		} else {
			token = getCookieValue(request, SSOUtil.tokenCookieNameSecure);
			return token;
		}
	}

	public static IssoClient getIssoClient(ServletContext ctx) throws Exception {
		String ssoURL = ctx.getInitParameter("ssoTokenURL");
		String ssoClientBean = ctx.getInitParameter("ssoClientBean");
		log.debug("context-param:ssoURL=" + ssoURL + " ssoClientBean="
				+ ssoClientBean);
		if (CM.stringIsEmpty(ssoClientBean)) {
			log.error("没有配置context-param：param-name=ssoClientBean");
			throw new Exception("没有配置context-param：param-name=ssoClientBean");
		}
		if ("ssoClientHttp".equals(ssoClientBean)) {
			IssoClient ssoClien = new SsoClientHttp();
			SsoClientHttp.setSsoURL(ssoURL);
			return ssoClien;
		}
		ApplicationContext context = WebApplicationContextUtils
				.getRequiredWebApplicationContext(ctx);
		IssoClient ssoClient = (IssoClient) context.getBean(ssoClientBean);
		if (ssoClient instanceof SsoClientHttp) {
			if (CM.stringIsEmpty(ssoURL)) {
				log.error("没有配置context-param：param-name=ssoTokenURL");
				throw new Exception("没有配置context-param：param-name=ssoTokenURL");
			} else {
				SsoClientHttp.setSsoURL(ssoURL);
			}
		}
		return ssoClient;
	}

}
